

package org.catpay.modules.sys.oauth2;

import java.io.Serializable;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.catpay.common.utils.Constant;
import org.catpay.common.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * shiro session dao
 *
 */
@Component
public class RedisShiroSessionDAO extends EnterpriseCacheSessionDAO {
	
    @Autowired
    private RedisUtils redisTemplate;
    
    //创建session
    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.doCreate(session);
        final String key = Constant.SESSION_ID + sessionId.toString();
        setShiroSession(key, session);
        return sessionId;
    }

    //获取session
    @Override
    protected Session doReadSession(Serializable sessionId) {
        Session session = super.doReadSession(sessionId);
        if(session == null){
            final String key = Constant.SESSION_ID + sessionId.toString();
            session = getShiroSession(key);
        }
        return session;
    }

    //更新session
    @Override
    protected void doUpdate(Session session) {
        super.doUpdate(session);
        final String key = Constant.SESSION_ID + session.getId().toString();
        setShiroSession(key, session);
    }

    //删除session
    @Override
    protected void doDelete(Session session) {
        super.doDelete(session);
        final String key = Constant.SESSION_ID + session.getId().toString();
        redisTemplate.delete(key);
    }

    private Session getShiroSession(String key) {
        return (Session)redisTemplate.getObj(key);
    }

    private void setShiroSession(String key, Session session){
        redisTemplate.setObj(key, session, 86400); //一天后自动清除redis
    }

}
